package com.jrx.anytxn.accounting.job.consolidationbilling.step;

import com.jrx.anytxn.accounting.bean.DealBillBean;
import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.item.ItemWriter;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

public class ConsolidationBillingWriter implements ItemWriter<GaVoucherInfo> {
    private Map<String, DealBillBean> subjectDetailMap;

    public ConsolidationBillingWriter(Map<String, DealBillBean> subjectDetailMap) {
        this.subjectDetailMap = subjectDetailMap;
    }

    private static ReentrantLock lock = new ReentrantLock();


    @Override
    public void write(List items) {
        Map<String, List<GaVoucherInfo>> gaVoucherInfoMap = ((List<GaVoucherInfo>) items).stream().collect(Collectors.groupingBy(GaVoucherInfo::getSubjectId));

        gaVoucherInfoMap.forEach(
                (subjectId, list) -> {
                    List<GaVoucherInfo> debitList = list.stream().filter(info -> "D".equals(info.getSign())).collect(Collectors.toList());
                    List<GaVoucherInfo> creditList = list.stream().filter(info -> "C".equals(info.getSign())).collect(Collectors.toList());

                    DealBillBean dealBillBean = new DealBillBean();
                    if (CollectionUtils.isNotEmpty(debitList)) {
                        dealBillBean.setDebitCount(debitList.size());
                        dealBillBean.setDebitAmount(debitList.stream().map(GaVoucherInfo::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                    }
                    if (CollectionUtils.isNotEmpty(creditList)) {
                        dealBillBean.setCreditCount(creditList.size());
                        dealBillBean.setCreditAmount(creditList.stream().map(GaVoucherInfo::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                    }
                    this.putDealBillBean(subjectId, dealBillBean);
                });
    }

    /**
     * 获取，修改缓存map加锁
     * @param subjectId
     * @param dealBillBean
     */
    private void putDealBillBean(String subjectId, DealBillBean dealBillBean) {
        lock.lock();
        try {
            if (null == subjectDetailMap.get(subjectId)) {
                subjectDetailMap.put(subjectId, dealBillBean);
            } else {
                subjectDetailMap.get(subjectId).add(dealBillBean);
            }
        } finally {
            lock.unlock();
        }

    }
}
